/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ee.persistence.dinamic;

import org.ee.persistence.dinamic.exception.SQLQueryNotFoundException;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;
import javax.xml.bind.JAXBException;
import org.apache.log4j.Logger;
import org.ee.xml.QueryDefinition;
import org.ee.xml.SqlQueries;
import org.ee.xml.XMLManager;

/**
 *
 * @author Gabriel Bran <gbran.u@gmail.com>
 */
@Startup
@Singleton
public class SQLQueryProducer {

    @Inject
    private transient Logger logger;
    private SqlQueries sqlQueries;

    @PostConstruct
    public void initialize() {
        try {
            sqlQueries = new XMLManager<SqlQueries>("/home/gbran/workspace/ee-model/src/java/queries-def.xml", SqlQueries.class).load();
        } catch (JAXBException e) {
            logger.error("Error al intentar cargar xml de consultas nativas: ", e);
        }
    }

    @Produces
    @DynamicSQLQuery
    public QueryDefinition findQuery(InjectionPoint injectionPoint) throws SQLQueryNotFoundException {
        if (injectionPoint.getAnnotated().isAnnotationPresent(QueryName.class)) {
            String queryName = injectionPoint.getAnnotated().getAnnotation(QueryName.class).value();
            for (QueryDefinition query : sqlQueries.getQueries()) {
                if (query.getName().equalsIgnoreCase(queryName)) {
                    return query;
                }
            }
            throw new SQLQueryNotFoundException("No se ha encontrado la consulta: ".concat(queryName));
        }
        throw new SQLQueryNotFoundException("Debe anotar el query con @QueryName");
    }
}
